// import io from 'socket.io-client'
import app from '@/store/modules/app';
import {
  SERVER_WS_URL
} from './config';
const CHAT = {
  username: '',
  roomid: '',
  userid: null,
  color: null,
  socket: null,
  status: 0,
  onlineCount: 0,
  onlineUsers: [],
  msgArr: [],
  //让浏览器滚动条保持在最低部
  scrollToBottom: function () {
    // window.scrollTo(0, 900000);
  },
  //登录
  join: function (rid) {
    this.roomid = rid;
    // console.log('this.roomid:', this.roomid)
    this.send(
      JSON.stringify({
        cmd: 'EVENT_JOIN',
        userid: this.userid,
        username: this.username,
        color: this.color,
        roomid: this.roomid,
        timestamp: Math.floor((new Date().getTime()) / 1000)
      })
    );
    this.status = 2;
  },
  //退出聊天室
  logout: function () {
    if (this.socket) {
      this.send(
        JSON.stringify({
          cmd: 'EVENT_LEAVE',
          userid: this.userid,
          username: this.username,
          roomid: this.roomid
        }));
    }
    console.log('CHAT.msgArr[i].userid:', this.msgArr);
    this.msgArr = [];
    // this.status=0
  },
  // 关闭websocket连接
  wsclose: function () {
    this.socket.close();
    this.status = 0;
    // this.status=0
  },
  // 发送消息给服务器
  send: function (obj) {
    if (!obj.length) {} else {
      this.socket.send(obj);
    }
  },
  //提交聊天消息内容
  submit: function (md) {
    if (md !== '') {
      let obj = JSON.stringify({
        cmd: 'EVENT_MESSAGE',
        username: this.username,
        roomid: this.roomid,
        userid: (this.userid),
        targetid: '',
        timestamp: Math.floor((new Date().getTime()) / 1000),
        msg: md
      });
      this.send(obj);
    } else {}

    return false;
  },
  //更新系统消息，本例中在用户加入、退出的时候调用
  updateSysMsg: function (o, action) {
    //当前在线用户列表
    this.onlineUsers = o.onlineUsers;
    //当前在线人数
    this.onlineCount = this.onlineUsers.length;
  },
  changeInfo () {
    this.userid = localStorage.getItem('userid');
    this.username = localStorage.getItem('name');
    this.color = localStorage.getItem('color');
    this.weichat = localStorage.getItem('weichat');
    this.socket.emit('changeInfo', {
      userid: this.userid,
      username: this.username,
      color: this.color,
      weichat: this.weichat
    });
  },
  init: function (Rid) {
    /*
     客户端根据时间和随机数生成uid,这样使得聊天室用户名称可以重复。
     实际项目中，如果是需要用户登录，那么直接采用用户的uid来做标识就可以
     */
    // this.userid = this.genUid();
    let STATUS = {
      WAIT: 0,
      CONNECTING: 1,
      CONNECTED: 3,
      JOINED: 2
    };
    let self = this;
    self.userid = app.state.userInfo.Id;
    self.username = app.state.userInfo.Abbr;
    self.roomid = Rid;
    // console.log('roomid:', self.roomid)
    // this.userid = localStorage.getItem('userid');
    // this.username = localStorage.getItem('name');
    self.color = localStorage.getItem('color');
    // this.weichat = localStorage.getItem('weichat');

    if (!self.userid) {
      return;
    }

    self.status = STATUS.CONNECTING;
    //连接websocket后端服务器
    self.socket = new WebSocket('ws://' + SERVER_WS_URL + '/ws/join?userid=' + self.userid + '&roomid=' + self.roomid);

    //监听连接建立
    self.socket.onopen = function () {
      self.join(Rid);
    };
    //监听连接断开，10秒后重连
    self.socket.onclose = function (evt) {
      self.status = STATUS.WAIT;
      setTimeout(() => {
        self.init();
      }, 10000);
    };
    //监听服务端消息
    self.socket.onmessage = function (obj) {
      let msg = JSON.parse(obj.data);
      // console.log('msg:',msg)
      switch (msg.cmd) {
      //监听用户退出
      case 'EVENT_LEAVE':
        self.updateSysMsg(msg, 'logout');
        msg.msg = msg.username + '退出聊天室' + msg.roomid;
        self.msgArr.push(msg);
        break;
        //监听新用户登录
      case 'EVENT_JOIN':
        self.updateSysMsg(msg, 'login');
        msg.msg = msg.username + '进入聊天室' + msg.roomid;
        self.msgArr.push(msg);
        setTimeout(() => {
          self.status = STATUS.JOINED;
        }, 500);
        break;
        //监听消息发送
      case 'EVENT_MESSAGE':
        self.msgArr.push(msg);
        break;
        //  其他系统消息
      default:
        CHAT.updateSysMsg(msg, 'logout');
        self.msgArr.push(msg);
        setTimeout(() => {
          self.status = STATUS.JOINED;
        }, 1500);
      }
    };
    // 监听错误
    self.socket.onerror = function () {
      self.status = STATUS.WAIT;
    };
  }
};
export default CHAT;
